package com.example.listener;


import com.example.common.util.SpringContextUtil;
import com.example.service.IActFlowCustomService;
import com.example.service.impl.PurtcServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.HistoryService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 处理整个审批走完时的逻辑
 */
@Slf4j
@Component
public class ActivityListener implements ExecutionListener {


    @Override
    public void notify(DelegateExecution delegateExecution) {
        String currentActivityId = delegateExecution.getCurrentActivityId();
        String processInstanceId = delegateExecution.getProcessInstanceId();
        //delegateExecution.getVariable("formKey");
        RuntimeService runtimeService = SpringContextUtil.getBean(RuntimeService.class);
        ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(processInstanceId).singleResult();
        runtimeService.setVariable(delegateExecution.getId(),"result","审批通过");
        String businessKey=processInstance.getBusinessKey();
        String[] split = businessKey.split(":");
        String formKey=split[0];
        String id=split[1]+":"+split[2];
        String initiator = runtimeService.getVariable(delegateExecution.getId(), "initiator", String.class);
        String beanName=formKey+"ServiceImpl";
        IActFlowCustomService customService = (IActFlowCustomService)SpringContextUtil.getBean(beanName);
        if (currentActivityId.equals("failed")){
            customService.endRunTask(id,false,delegateExecution.getProcessDefinitionId(),initiator);
        } else if (currentActivityId.equals("success")) {
            customService.endRunTask(id,true,delegateExecution.getProcessDefinitionId(),initiator);
        }
    }
}
